package com.lingx.web.api;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.service.LingxService;


@Component
public class ApiService {
	@Resource
	private List<IApi> listApi;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private LingxService lingxService;
	
	@PostConstruct
	public void init() {
		//默认给超管角色授权所有API
		String roleId=lingxService.getConfigValue("lingx.super.role.code", "6e0362e8-100e-11e5-b7ab-74d02b6b5f61");//lingx.super.role.code
		int apicode=0;
		for(IApi api:this.listApi) {
			apicode=api.getApiCode();
			if(this.jdbcTemplate.queryForObject("select count(*) from tlingx_role_api where role_id=? and apicode=?", Integer.class,roleId,apicode)==0) {
				this.jdbcTemplate.update("insert into tlingx_role_api(id,role_id,apicode)values(?,?,?)",this.lingxService.uuid(),roleId,apicode);
			}
		}
	}
	
	public Map<String,Object> callApi(Map<String,Object> params){
		if(!params.containsKey("apicode")) {
			return IApi.getRetMap(-1, "请求参数apicode不可为空");
		}
		Map<String,Object> ret=null;
		try {
			for(IApi api:this.listApi) {
				if(api.getApiCode()==Integer.parseInt(params.get("apicode").toString())) {
					int errorCode=api.before(params);
					if(errorCode==0) {
						ret=api.api(params);
						break;
					}else {
						ret= IApi.getRetMap(errorCode, "无权限");
					}
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret= IApi.getRetMap(-1, params.get("apicode")+"接口异常:"+e.getLocalizedMessage());
		}
		if(ret==null) {
			ret= IApi.getRetMap(-1, params.get("apicode")+"接口未实现");
		}
		return ret;
	}
	
	/**
	 * 内部直接调用，不需要验证
	 * @param params
	 * @return
	 */
	public Map<String,Object> callApiByLingx(Map<String,Object> params){
		if(!params.containsKey("apicode")) {
			return IApi.getRetMap(-1, "请求参数apicode不可为空");
		}
		Map<String,Object> ret=null;
		try {
			for(IApi api:this.listApi) {
				if(api.getApiCode()==Integer.parseInt(params.get("apicode").toString())) {
					ret=api.api(params);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret= IApi.getRetMap(-1, params.get("apicode")+"接口异常:"+e.getLocalizedMessage());
		}
		if(ret==null) {
			ret= IApi.getRetMap(-1, params.get("apicode")+"接口未实现");
		}
		return ret;
	}
	
	
}
